package kr.co.graviti.common.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.graviti.adm.common.dao.AdmCommonDAO;
import kr.co.graviti.common.util.CommonUtil;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class CommonAdmDownLoadAction extends BaseFuncAction  {
	
private static final Logger _log = Logger.getLogger(CommonAdmDownLoadAction.class);
	
	public ActionForward execute(ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		
		HashMap req = null;
		req = CommonUtil.getRequest(request);
		req.put("attch_file_info_idx", req.get("idx"));
		req.put("attch_file_idx", req.get("seq"));
		HashMap filemap = new AdmCommonDAO().getHashMapDAO(req, "admBbs.selectAttFileInfo");
		
		String orgFileNm = CommonUtil.strNullChk((String)filemap.get("ORG_FILENM"));
		String saveFileNm = CommonUtil.strNullChk((String)filemap.get("CHG_FILENM"));
		String path	= BBS_DEFAULT_PATH + req.get("board_type") + "/";
		// 파일 다운로드 버퍼 생성 
		
		
		File f = new File(path+saveFileNm);	
		String returnnm = "";
		if(!f.exists()){
			returnnm = "fail";
			request.setAttribute("msg", "No File");
			_log.info("No File");
		}else{
			returnnm = "success";
			request.setAttribute("msg", "");
			
			response.setHeader("Content-Disposition", "attachment; filename=\"" + CommonUtil.toEng(orgFileNm) + "\";");
			response.setHeader("Content-Transfer-Encoding", "UTF-8");
			
			orgFileNm	= new String(orgFileNm.getBytes("euc-kr"),"8859_1");
			byte b[] = new byte[4096];
			response.setHeader("Content-Disposition", "attachment; filename=" + orgFileNm + ";");
			BufferedInputStream fin = new BufferedInputStream(new FileInputStream(f));
			BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
			
			int read = 0;
			while ((read = fin.read(b)) != -1){
				  outs.write(b,0,read);
			}//while
			outs.close();
			fin.close();
		}
		
		return mapping.findForward(returnnm);
	}
}
